package com.example.haoqisystem.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.example.haoqisystem.Utils.ConstUtil;
import com.example.haoqisystem.Utils.PageUtil;
import com.example.haoqisystem.entity.TrainningApplication;
import com.example.haoqisystem.entity.TrainningPlan;
import com.example.haoqisystem.request.CreateTrainningPlanRequest;
import com.example.haoqisystem.request.QueryTrainningPlanListRequest;
import com.example.haoqisystem.request.UpdateTrainningPlanRequest;
import com.example.haoqisystem.response.BaseResponse;
import com.example.haoqisystem.response.PageResult;
import com.example.haoqisystem.respository.TrainningApplicationRepository;
import com.example.haoqisystem.respository.TrainningPlanRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

@Service
@Slf4j
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class TrainPlanService {
    private final TrainningPlanRepository trainningPlanRepository;
    public final TrainningApplicationRepository trainningApplicationRepository;

    //新增培训计划
    public BaseResponse<TrainningPlan> add(CreateTrainningPlanRequest request) {
        if(request.getTrainningApplicationId()==null||request.getTrainningApplicationId().equals(""))
        {
            return new BaseResponse<>("培训申请id不能为空！",false,null);
        }
        try{
            TrainningPlan plan=new TrainningPlan();
            BeanUtil.copyProperties(request,plan, CopyOptions.create().setIgnoreNullValue(true));
            //相应的培训申请保存培训计划id
            Optional<TrainningApplication> applicationOptional=trainningApplicationRepository.findById(request.getTrainningApplicationId());
            if(!applicationOptional.isPresent()){
                return new BaseResponse<>("该申请不存在!",false,null);
            }
            plan.setIsGenerateLecture(false);
            TrainningPlan plan1=trainningPlanRepository.save(plan);
            TrainningApplication application=applicationOptional.get();
            application.setTrainningPlanId(plan1.getId());
            application.setIsGeneratePlan(true);
            trainningApplicationRepository.save(application);
            return new BaseResponse<>(ConstUtil.CREATE_SUCCESS,true,plan1);
        }catch (Exception e){
            return new BaseResponse<>(e.toString(), true,null);
        }
    }

    //查看培训计划详情
    public BaseResponse<TrainningPlan> detail(Long id) {
        try{
            Optional<TrainningPlan> optionalTrainningPlan=trainningPlanRepository.findById(id);
            if(!optionalTrainningPlan.isPresent()){
                return new BaseResponse<>("该培训计划不存在！",false,null);
            }
            TrainningPlan plan=optionalTrainningPlan.get();
            return new BaseResponse<>(ConstUtil.QUERY_SUCCESS,true,plan);
        }catch (Exception e){
            return new BaseResponse<>(e.toString(),false,null);
        }
    }

    //更新培训计划
    public BaseResponse<TrainningPlan> update(UpdateTrainningPlanRequest request) {
        try{
            Optional<TrainningPlan> trainningPlanOptional=trainningPlanRepository.findById(request.getId());
            if(!trainningPlanOptional.isPresent()){
                return new BaseResponse<>("该培训计划不存在！",false,null);
            }
            TrainningPlan plan=trainningPlanOptional.get();
            BeanUtil.copyProperties(request,plan,CopyOptions.create().setIgnoreNullValue(true));
            return new BaseResponse<>(ConstUtil.UPDATE_SUCESS,true,trainningPlanRepository.save(plan));
        }catch (Exception e){
            return new BaseResponse<>(e.toString(),false,null);
        }
    }

    //删除培训计划
    @Transactional(rollbackFor = Exception.class)
    public BaseResponse<String> delete(Long id) {
        Optional<TrainningPlan> optional=trainningPlanRepository.findByIdAndDeletedFalse(id);
        if(!optional.isPresent()){
            return new BaseResponse<>("该计划不存在！",false,null);
        }
        TrainningPlan plan=optional.get();
        plan.setDeleted(true);
        trainningPlanRepository.save(plan);
        //对应得的培训申请
        Optional<TrainningApplication> applicationOptional=trainningApplicationRepository.findByIdAndDeletedFalse(plan.getTrainningApplicationId());
        if(applicationOptional.isPresent()){
            TrainningApplication application=applicationOptional.get();
            application.setIsGeneratePlan(false);
            trainningApplicationRepository.save(application);
        }
        return new BaseResponse<>(ConstUtil.DELETED_SUCCESS,true,"删除成功！");
    }

    //查询培训计划列表
    public BaseResponse<PageResult<TrainningPlan>> queryList(QueryTrainningPlanListRequest request) {
        try{
            Specification<TrainningPlan> specification=(root, query, builder) -> {
                List<Predicate> predicates=new ArrayList<>();
                //TODO: 其他分页查询条件，字段还未完全确认
                predicates.add(builder.equal(root.get("deleted"),request.isDeleted()));
                return builder.and(predicates.toArray(new Predicate[0]));
            };
            List<TrainningPlan> list=trainningPlanRepository.findAll(specification);
            Collections.reverse(list);
            PageResult<TrainningPlan> page= PageUtil.getPage(list,request.getPageNum(),request.getPageSize());
            return new BaseResponse<>(ConstUtil.QUERY_SUCCESS,true,page);
        }catch (Exception e){
            return new BaseResponse<>(e.toString(),false,null);
        }
    }

    //全部培训计划列表
    public BaseResponse<List<TrainningPlan>> queryList1(boolean deleted, String lectureName,Boolean isGenerateLecture,Long id) {
        try{
            Specification<TrainningPlan> specification=(root, query, builder) -> {
                List<Predicate> predicates=new ArrayList<>();
                if(lectureName!=null&&!lectureName.equals("")){
                    String nameLike="%"+lectureName+"%";
                    predicates.add(builder.like(root.get("lectureName"),nameLike));
                }
                if(isGenerateLecture!=null&&!isGenerateLecture.equals("")){
                    predicates.add(builder.equal(root.get("isGenerateLecture"),isGenerateLecture));
                }
                if(id!=null&&!id.equals("")){
                    predicates.add(builder.equal(root.get("id"),id));
                }
                predicates.add(builder.equal(root.get("deleted"),deleted));
                return builder.and(predicates.toArray(new Predicate[0]));
            };

            List<TrainningPlan> plans=trainningPlanRepository.findAll(specification);
            Collections.reverse(plans);
            return new BaseResponse<>(ConstUtil.QUERY_SUCCESS,true,plans);
        }catch (Exception e){
            return new BaseResponse<>(e.toString(),false,null);
        }
    }
}
